<template>
  <div style="width: 100vw;height: 100vh;display: flex;flex-direction: column;overflow: hidden;">
    <div style="height: 10vh; background-color: #f5f5f5; min-height: 60px; flex-shrink: 0;">
      <el-row :gutter="10">
        <el-col :span="1">
          <img src="../../../public/imgs/login/leaf.png" style="height: 40px; padding-top: 13px; padding-left: 16px;">
        </el-col>
        <el-col :span="15">
          <span style="font-size: 25px; color: #35984b; padding-left: 40px; line-height: 10vh;font-weight: bold;">垃圾分类管理项目后台</span>
        </el-col>
      </el-row>
    </div>

    <div style="display: flex; height: 90vh;">
      <!-- 左侧菜单栏 -->
      <div style="width: 228px">
        <el-menu
            background-color="#35984b"
            style="width: 100%; height: 100vh; border: none;"
            text-color="#fff"
            active-text-color="#fff"
            router
            :collapse-transition="true"
        >
          <el-menu-item index="/adminNotice">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Promotion /></el-icon>
              <span class="left-menu-item">资讯管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminGarbage">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><DeleteFilled /></el-icon>
              <span class="left-menu-item">垃圾管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminUser">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><UserFilled /></el-icon>
              <span class="left-menu-item">用户管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminPut">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><CircleCheckFilled /></el-icon>
              <span class="left-menu-item">投放管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/admin">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Avatar /></el-icon>
              <span class="left-menu-item">个人中心</span>
            </template>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧顶部条与主体内容（可变区域）-->
      <div style="width: calc(100% - 228px)">
        <el-header style="height: 80px; background-color: #fff; padding-top: 22px;">
          <el-row>
            <!-- 登录人姓名和退出登录 -->
            <el-col :span="24">
              <div style="display: flex; justify-content: space-between; align-items: center; height: 100%; padding:0 20px;">
                <!-- 面包屑导航 -->
                <el-breadcrumb separator="/" style="margin-left: 10px;">
                  <el-breadcrumb-item
                      v-for="item in breadcrumb"
                      style="font-size: 16px; font-weight: 500;"
                  >
                    | {{ item }}
                  </el-breadcrumb-item>
                </el-breadcrumb>

                <!-- 用户信息 -->
                <div>
                  <el-dropdown trigger="click">
                    <div style="display: flex; align-items: center; cursor: pointer; padding: 8px 12px; border-radius: 4px;">
                      <el-icon><User /></el-icon>
                      <span style="font-size: 16px; font-weight: 500; color: #606266; margin-left: 8px; margin-right: 8px;">{{ user.username }}</span>
                      <el-icon><ArrowDown /></el-icon>
                    </div>
                    <template #dropdown>
                      <el-dropdown-menu style="--el-dropdown-menuItem-hover-fill: #f6f6f6; --el-dropdown-menuItem-hover-color: #008800;">
                        <el-dropdown-item @click="toAdmin">
                          <el-icon><Avatar /></el-icon>个人中心
                        </el-dropdown-item>
                        <el-dropdown-item @click="logout" divided>
                          <el-icon><SwitchButton /></el-icon>退出登录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-header>
        <!-- 右侧主体内容 -->
        <el-main style=" padding: 0; height: calc(100vh - 10vh - 100px); overflow-y: auto;">
        <!-- 投放记录搜索卡片 -->
        <el-card style="margin: 10px;height: 70px;">
          <el-form :inline="true">
            <el-form-item label="垃圾名称" style="width: 270px;">
              <el-input placeholder="请输入用户名" v-model="searchRecordForm.name"></el-input>
            </el-form-item>
            <el-form-item label="垃圾类别" style="width: 290px;">
              <el-select placeholder="请选择垃圾类别" v-model="searchRecordForm.category">
                <el-option label="可回收垃圾" value="可回收垃圾"></el-option>
                <el-option label="有害垃圾" value="有害垃圾"></el-option>
                <el-option label="厨余垃圾" value="厨余垃圾"></el-option>
                <el-option label="其他垃圾" value="其他垃圾"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态" style="width: 290px;">
              <el-select placeholder="请选择审核状态" v-model="searchRecordForm.status">
                <el-option label="未审核" value="10"></el-option>
                <el-option label="审核通过" value="20"></el-option>
                <el-option label="审核未通过" value="30"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="info" @click="resetSearch">重置</el-button>
              <el-button type="success" @click="loadRecord">搜索</el-button>
            </el-form-item>
          </el-form>

        </el-card>
        <!-- 投放记录表格卡片 -->
        <el-card style="margin: 10px; display: flex; flex-direction: column; min-height: calc(100% - 10vh - 100px);">
          <el-table :data="pagedRecordArr" style="flex: 1;">
            <el-table-column type="index" label="序号" width="80" align="center">
              <template #default="scope">
                {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="userId" label="投放人" align="center">
              <template #default="scope">
                {{ getUserName(scope.row.userId) }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="垃圾名称" align="center"></el-table-column>
            <el-table-column prop="category" label="垃圾类别" align="center"></el-table-column>
            <el-table-column prop="createTime" label="投放时间" align="center"></el-table-column>
            <el-table-column prop="num" label="数量（份）" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" align="center">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                    type="success"
                    link
                    @click="showReviewDialog(scope.row)"
                    :disabled="scope.row.status !== 10"
                >
                审核
                </el-button>
                <el-button type="danger" link @click="deleteRecord(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 审核对话框 -->
          <el-dialog
              v-model="reviewDialogVisible"
              title="投放记录审核"
              width="30%"
              :close-on-click-modal="false">

            <el-descriptions :column="1" border>
              <el-descriptions-item label="投放人">{{ currentRecord.userName || getUserName(currentRecord.userId) }}</el-descriptions-item>
              <el-descriptions-item label="垃圾名称">{{ currentRecord.name }}</el-descriptions-item>
              <el-descriptions-item label="垃圾类别">{{ currentRecord.category }}</el-descriptions-item>
              <el-descriptions-item label="投放时间">{{ currentRecord.createTime }}</el-descriptions-item>
              <el-descriptions-item label="投放数量">{{ currentRecord.num }}份</el-descriptions-item>
            </el-descriptions>

            <template #footer>
              <el-button @click="handleReview('reject')" type="danger">不通过</el-button>
              <el-button @click="handleReview('approve')" type="success">通过</el-button>
              <el-button @click="reviewDialogVisible = false" type="info">取消</el-button>
            </template>
          </el-dialog>

          <!-- 积分输入对话框 -->
          <el-dialog
              v-model="scoreDialogVisible"
              title="增加用户积分"
              width="30%"
              :close-on-click-modal="false">
            <el-form>
              <el-form-item label="增加积分" required>
                <el-input-number
                    v-model="addScore"
                    :min="1"
                    :step="1"
                    placeholder="请输入增加的积分"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="scoreDialogVisible = false" type="info">取消</el-button>
              <el-button
                  @click="confirmAddScore"
                  type="success"
                  :disabled="!addScore || addScore < 1"
              >
                确定
              </el-button>
            </template>
          </el-dialog>

          <!-- 分页组件 -->
          <div style="padding: 20px 0; text-align: center;">
            <el-pagination
                layout="prev, pager, next"
                :total="recordArr.length"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="handlePageChange"
            />
          </div>
        </el-card>
        </el-main>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  Message,
  Delete,
  User,
  Avatar,
  ArrowDown,
  SwitchButton
} from '@element-plus/icons-vue'
import axios from "axios";
import qs from "qs";

// 获取当前登录用户的信息
const user = ref(getUser());

const toAdmin = () => {
  router.push('/admin');
}
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    localStorage.removeItem('user');
    window.location.href = '/login';
    user.value = '';
  }).catch(()=>{

  })
}
// 更新面包屑映射
let map = {
  '/adminNotice': ['资讯管理'],
  '/adminGarbage': ['垃圾管理'],
  '/admin': ['个人中心'],
  '/adminUser': ['用户管理'],
  '/adminPut': ['投放管理'],
}

const breadcrumb = ref([]);
const route = useRoute();
const router = useRouter();

onMounted(() => {
  updateBreadcrumb(route);
})
// 定义更新面包屑导航值的方法
const updateBreadcrumb = (route) => {
  const path = route.path;
  breadcrumb.value = map[path] || [];
}
// 监听路由变化，更新面包屑
router.beforeEach((to, from, next) => {
  updateBreadcrumb(to);
  next();
})

const recordArr  = ref([]);
const searchRecordForm = ref({name:'', category:'', status:''});
const recordForm = ref({
  name:'',
  category:'',
  img:'',
  num:'',
  status:'',
});
const loadRecord = () => {
  let data = qs.stringify(searchRecordForm.value);
  axios.get('http://localhost:8080/v1/record/select?'+data).then((response)=>{
    if(response.data.code == 2000){
      recordArr.value = response.data.data;
      currentPage.value = 1; // 搜索后重置到第一页
    }else{
      ElMessage.error(response.data.msg);
    }
  })
};
onMounted(()=>{
  loadRecord();
})
const resetSearch = ()=>{
  searchRecordForm.value = {};
  loadRecord();
}
// 创建userList响应式数组存储用户数据
const userList = ref([]);

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await axios.get('http://localhost:8080/v1/user/select')
    userList.value = response.data.data;
    console.log('用户列表:', userList.value);
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 根据用户ID和用户名的映射关系显示对应投放人的用户名
const getUserName = (userId) => {
  const user = userList.value.find(user => user.id == userId)
  return user ? user.username : '未知用户(ID: ${userId})'
}
// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers();
  loadRecord();
})

// 审核对话框相关变量
const reviewDialogVisible = ref(false)
const currentRecord = ref({})
const scoreDialogVisible = ref(false)
const addScore = ref(0) // 新增积分输入框绑定值

// 显示审核对话框
const showReviewDialog = (record) => {
  currentRecord.value = { ...record }
  reviewDialogVisible.value = true
}

// 处理审核操作
const handleReview = async (action) => {
  try {
    if (action === 'approve') {
      // 通过审核时显示积分输入对话框
      scoreDialogVisible.value = true
    } else {
      const url = `http://localhost:8080/v1/record/reject/${currentRecord.value.id}`
      const response = await axios.post(url)

      if (response.data.code === 2000) {
        ElMessage.success('审核不通过')
        // 更新本地记录状态
        const index = recordArr.value.findIndex(r => r.id === currentRecord.value.id)
        if (index !== -1) {
          recordArr.value[index].status = 30 // 审核不通过状态
        }
        reviewDialogVisible.value = false
      } else {
        ElMessage.error(response.data.msg)
      }
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  }
}

// 确认增加积分并审核通过
const confirmAddScore = async () => {
  try {
    const points = parseInt(addScore.value)
    if (isNaN(points) || points < 0) {
      ElMessage.warning('请输入有效的积分值')
      return
    }

    const url = `http://localhost:8080/v1/record/approve/${currentRecord.value.id}`
    const response = await axios.post(url, null, { params: { points } })

    if (response.data.code === 2000) {
      ElMessage.success('审核已通过，积分增加成功')

      // 更新本地记录状态
      const index = recordArr.value.findIndex(r => r.id === currentRecord.value.id)
      if (index !== -1) {
        recordArr.value[index].status = 20 // 审核通过状态
      }

      // 更新用户列表中的积分
      const userId = currentRecord.value.userId
      const userIndex = userList.value.findIndex(u => u.id === userId)
      if (userIndex !== -1) {
        userList.value[userIndex].points += points
      }

      scoreDialogVisible.value = false
      reviewDialogVisible.value = false
      addScore.value = 0 // 重置积分输入
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  }

}

const getStatusText = (statusCode) => {
  switch(statusCode) {
    case 10: return '未审核'
    case 20: return '审核通过'
    case 30: return '审核未通过'
    default: return '未知状态'
  }
}

const getStatusTagType = (statusCode) => {
  switch(statusCode) {
    case 10: return 'primary'
    case 20: return 'success'
    case 30: return 'danger'
    default: return 'info'
  }
}

const deleteRecord = (id) => {
  ElMessageBox.confirm('确定删除该条投放记录吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    axios.post('http://localhost:8080/v1/record/delete/' + id)
        .then((response) => {
          if (response.data.code == 2000) {
            ElMessage.success('删除成功!');
            loadRecord();
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch((error) => {
          ElMessage.error('删除投放记录时发生错误');
          console.error(error);
        });
  }).catch(() => {

  });
}

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(7);

// 计算属性：返回当前页的数据
const pagedRecordArr = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return recordArr.value.slice(start, end);
});

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};
</script>

<style scoped>
.left-menu-item {
  font-size: 18px;
  padding-left: 12px;
}

.left-menu-collapse-item {
  font-size: 17px;
  border: none;
  height: 40px;
}

/* 自定义滚动条样式 */
.el-main::-webkit-scrollbar {
  width: 8px;
}

.el-main::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

.el-main::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.el-pagination {
  justify-content: center;
}

.record-container {
  padding: 20px;
}
</style>